package com.nuanshui.heatedloan.credit.service;

import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.security.DESC;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.AuditOperationConstant;
import com.nuanshui.heatedloan.credit.constant.BorrowType;
import com.nuanshui.heatedloan.credit.constant.CreditAuditConstant;
import com.nuanshui.heatedloan.credit.dal.mapper.CustomerCreditAuditMapper;
import com.nuanshui.heatedloan.credit.facade.*;
import com.nuanshui.heatedloan.credit.facade.third.party.RiskManagerInteractionService;
import com.nuanshui.heatedloan.credit.form.CustomerCreditAuditForm;
import com.nuanshui.heatedloan.credit.model.AuditRequestParam;
import com.nuanshui.heatedloan.credit.model.CreditAuditDetail;
import com.nuanshui.heatedloan.credit.model.CreditAuditInfo;
import com.nuanshui.heatedloan.credit.model.record.OrderContactRecord;
import com.nuanshui.heatedloan.credit.model.record.OrderPhoneRecord;
import com.nuanshui.heatedloan.credit.model.record.OrderSmsRecord;
import com.nuanshui.heatedloan.credit.mongodb.OrderContactRecordRepository;
import com.nuanshui.heatedloan.credit.mongodb.OrderPhoneRecordRepository;
import com.nuanshui.heatedloan.credit.mongodb.OrderSmsUserRecordRepository;
import com.nuanshui.heatedloan.credit.request.*;
import com.nuanshui.heatedloan.credit.response.*;
import com.nuanshui.heatedloan.credit.vo.*;
import com.nuanshui.heatedloan.pageable.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangxw on 2017/7/29.
 */

@Service(ServiceConstant.CUSTOMERCREDITAUDITSERVICE)
@Transactional(readOnly=true,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
public class CustomerCreditAuditServiceImpl implements CustomerCreditAuditService {

    @Autowired
    private CustomerCreditAuditMapper customerCreditAuditMapper;

    @Autowired
    private CustomerIdCardInfoService  customerIdCardInfoService;   //客户基本信息

    @Autowired
    private CustomerBankCardInfoService customerBankCardInfoService;   //银行卡信息

    @Autowired
    private CustomerPeopleRelationshipService customerPeopleRelationshipService;  //客户人员关系

    @Autowired
    private CustomerCompanyInfoService customerCompanyInfoService;   //客户公司信息

    @Autowired
    private PayOrderInfoService payOrderInfoService;   //订单信息

    @Autowired
    private OrderSmsUserRecordRepository orderSmsUserRecordRepository;  //短信信息

    @Autowired
    private OrderPhoneRecordRepository orderPhoneRecordRepository;  //通话记录信息

    @Autowired
    private OrderContactRecordRepository orderContactRecordRepository;  //通讯录

    @Autowired
    private RiskManagerInteractionService riskManagerInteractionService;

    @Override
    public Pager<CreditAuditInfo> getCreditAuditInfo(int type, Pager<CreditAuditInfo> pager, AuditRequestParam param) {
        List<CreditAuditInfo> creditAuditInfos = customerCreditAuditMapper.getCreditAuditInfo(type,pager,param);
        this.dealCreditAuditInfo(creditAuditInfos);
        pager.setData(creditAuditInfos);
        return pager;
    }

    @Override
    public Pager<ClosedDetailed> getHistoryCreditAuditInfo(Pager<ClosedDetailed> pager, AuditRequestParam param) {
        int pageNumber=pager.getPageNumber();
        int numPerPage=pager.getPageSize();
        ClosedDetailedRequest closedDetailedRequest=new ClosedDetailedRequest();
        closedDetailedRequest.setPhoneNum(param.getPhone());
        closedDetailedRequest.setClosedState(param.getCaseEndStatus());
        closedDetailedRequest.setOrderNumber(param.getOrderId());
        closedDetailedRequest.setPage(pageNumber);
        closedDetailedRequest.setPagesize(numPerPage);
        ClosedDetailedResponse closedDetailedResponse=new ClosedDetailedResponse();
        closedDetailedResponse=riskManagerInteractionService.getHistoryCreditAudit(closedDetailedRequest);
        List<ClosedDetailed> closedDetaileds=new ArrayList<ClosedDetailed>();
        if(closedDetailedResponse!=null){
            closedDetaileds = closedDetailedResponse.getClosedDetailedList();
            for(ClosedDetailed closedDetailed:closedDetaileds){
                PayOrderInfoVO payOrderInfoVO=payOrderInfoService.loadVOByOrderNo(closedDetailed.getOrderId());
                if(BorrowType.SINGLELOAN==payOrderInfoVO.getBorrowType()||
                        BorrowType.LIGHTLOAN==payOrderInfoVO.getBorrowType()){
                    closedDetailed.setLoanPeriods( payOrderInfoVO.getLoadDays()+"天");
                }else{
                    closedDetailed.setLoanPeriods( payOrderInfoVO.getLoadDays()+"期");
                }
            }
        }
        pager.setData(closedDetaileds);
        pager.setTotal(closedDetailedResponse.getCount());
        return pager;
    }

    private void dealCreditAuditInfo(List<CreditAuditInfo> creditAuditInfos){
        for(CreditAuditInfo creditAuditInfo:creditAuditInfos){
            String loanDay=creditAuditInfo.getLoadDay();
            if(creditAuditInfo.getBorrowType()== BorrowType.SINGLELOAN||
                    creditAuditInfo.getBorrowType()==BorrowType.LIGHTLOAN){
                 loanDay=loanDay+"天";
            }else if(creditAuditInfo.getBorrowType()==BorrowType.INSTALLMENT){
                loanDay=loanDay+"期";
            }
            creditAuditInfo.setLoadDay(loanDay);
        }
    }

    @Override
    public CreditAuditDetail getCreditAuditInfoVO(String orderId){
        CreditAuditDetail creditAuditDetail =new CreditAuditDetail();
        //订单信息
        PayOrderInfoVO payOrderInfoVO=payOrderInfoService.loadVOByOrderNo(orderId);
        //银行卡信息
        CustomerBankCardInfoVO customerBankCardInfoVO=customerBankCardInfoService.loadVOByMixCardNo(payOrderInfoVO.getMixCardNo());
        customerBankCardInfoVO.setCardNo(DESC.decrypt3DES(customerBankCardInfoVO.getMixCardNo()));
        creditAuditDetail.setCustomerBankCardInfoVO(customerBankCardInfoVO);
        String orderMixCardNo=payOrderInfoVO.getMixCardNo();
        String orderCardNo=DESC.decrypt3DES(orderMixCardNo);
        payOrderInfoVO.setMixCardNo(orderCardNo);
        creditAuditDetail.setPayOrderInfoVO(payOrderInfoVO);
        //客户基本信息
        CustomerIdCardInfoVO customerIdCardInfoVO=customerIdCardInfoService.loadByUserId(payOrderInfoVO.getUserId());
        customerIdCardInfoVO.setIdCard(DESC.decrypt3DES(customerIdCardInfoVO.getIdCard()));
        creditAuditDetail.setCustomerIdCardInfoVO(customerIdCardInfoVO);

        //公司信息
        CustomerCompanyInfoVO customerCompanyInfoVO=customerCompanyInfoService.loadVOByUserId(payOrderInfoVO.getUserId());
        creditAuditDetail.setCustomerCompanyInfoVO(customerCompanyInfoVO);
        //人员关系信息
        List<CustomerPeopleRelationshipVO> customerPeopleRelationshipVO=customerPeopleRelationshipService.
                loadcustomerPeopleRelationshipVOByCusId(payOrderInfoVO.getUserId());
        creditAuditDetail.setCustomerPeopleRelationshipVO(customerPeopleRelationshipVO);
        //通讯率，通话记录，短信的设置
        this.getCreditAuditPhoneInfo(orderId,creditAuditDetail);
        //芝麻
        this.setSesameInfo(creditAuditDetail);
        //设置注记相关信息
        this.getLetterTrialNote(orderId,creditAuditDetail);
        return creditAuditDetail;
    }

    private void setSesameInfo(CreditAuditDetail creditAuditDetail){
        SelectSesameRequest selectSesameRequest=new SelectSesameRequest();
        selectSesameRequest.setOrderId(creditAuditDetail.getPayOrderInfoVO().getOrderNo());
        selectSesameRequest.setCustomerId(creditAuditDetail.getPayOrderInfoVO().getUserId());
        SelectSesameResponse selectSesameResponse=riskManagerInteractionService.selectSesameInfo(selectSesameRequest);
        creditAuditDetail.setSelectSesameResponse(selectSesameResponse);
    }

    @Override
    public void getCreditAuditPhoneInfo(String orderId,CreditAuditDetail creditAuditDetail) {
         List<OrderContactRecord> orderContactRecords=orderContactRecordRepository.findByOrderNo(orderId);
            for(OrderContactRecord orderContactRecord:orderContactRecords){
                String mixName=orderContactRecord.getName();
                String mixPhone=orderContactRecord.getPhone();
                orderContactRecord.setPhone(mixName);
                orderContactRecord.setName(mixPhone);
            }
            creditAuditDetail.setContactRecord(orderContactRecords);
            //电话记录
            List<OrderPhoneRecord> orderPhoneRecord=orderPhoneRecordRepository.findByOrderNo(orderId);
            creditAuditDetail.setPhoneRecord(orderPhoneRecord);
            //短信
            List<OrderSmsRecord> orderSmsRecord=orderSmsUserRecordRepository.findByOrderNo(orderId);
           creditAuditDetail.setSmsRecord(orderSmsRecord);

    }

    @Override
    public void save(CustomerCreditAuditForm CustomerCreditAuditForm) {
        customerCreditAuditMapper.save(CustomerCreditAuditForm);
    }

    /***
     *
     * @param orderId
     * @return
     */
    public List<OperationLogContent> getOperationLog(String orderId){
        List<OperationLogContent> operationLogContent=new ArrayList<OperationLogContent>();
        SelectOperationLogRequest selectOperationLogRequest=new SelectOperationLogRequest();
        selectOperationLogRequest.setOrderId(orderId);
        SelectOperationLogResponse  selectOperationLogResponse=riskManagerInteractionService.
                getOperationLog(selectOperationLogRequest);
        if(selectOperationLogResponse!=null){
            operationLogContent=selectOperationLogResponse.getOperationLogContent();
        }
        return operationLogContent;
    }
    /***
     * 查询信审注记
     * @param orderId
     * @return
     */
    public void getLetterTrialNote(String orderId,CreditAuditDetail creditAuditDetail){
        SelectLetterTrialNoteResponse selectLetterTrialNoteResponse=new  SelectLetterTrialNoteResponse();
        SelectLetterTrialNoteRequest selectLetterTrialNoteRequest=new SelectLetterTrialNoteRequest();
        selectLetterTrialNoteRequest.setOrderId(orderId);
        selectLetterTrialNoteResponse=riskManagerInteractionService.getLetterTrialNote(selectLetterTrialNoteRequest);
        if(selectLetterTrialNoteResponse!=null){
            creditAuditDetail.setSelectLetterTrialNoteResponse(selectLetterTrialNoteResponse);
        }
    }

    /***
     * 调用风控的接口插入日志
     * @param operationLogRequest
     *
     */
    private RiskBaseResponse saveOperationLog( OperationLogRequest operationLogRequest ){
       String date= DateUtil.getToday("yyyy-MM-dd HH:mm:ss");
        operationLogRequest.setOperationTime(date);
        RiskBaseResponse  riskBaseResponse=riskManagerInteractionService.saveOperationLog(operationLogRequest);
        return riskBaseResponse;
    }

    /***
     * 保存审信注记信息
     * @param letterTrialNote
     * 1  提交 2  暂存  3 内部回退 坑爹需求
     */
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void create(LetterTrialNote letterTrialNote,int type,String userId){
        LetterTrialNoteRequest letterTrialNoteRequest=new LetterTrialNoteRequest();

        BeanUtils.copyProperties(letterTrialNote,letterTrialNoteRequest);
        RiskBaseResponse riskBaseResponse=riskManagerInteractionService.saveTrialNote(letterTrialNoteRequest);
        if(riskBaseResponse==null){
            return;
        }
        //更新数据库状态
        List<CustomerCreditAuditForm> customerCreditAuditForms=new ArrayList<CustomerCreditAuditForm>();
        String orderId=letterTrialNoteRequest.getOrderId();
        CustomerCreditAuditForm customerCreditAuditForm=new CustomerCreditAuditForm();
        customerCreditAuditForm.setOrderId(orderId);
        customerCreditAuditForm.setStatus(1);
        customerCreditAuditForm.setAuditConclusion(letterTrialNoteRequest.getLettertrialConclusion());
        if(2==type){
            customerCreditAuditForm.setReviewer(letterTrialNote.getOperationId());
        }
        customerCreditAuditForms.add(customerCreditAuditForm);
        if(2==type){
            customerCreditAuditForm.setAuditStatus(CreditAuditConstant.TRIALSAVE);
            customerCreditAuditForm.setUserId(userId);
            this.distributionOrder(customerCreditAuditForms,AuditOperationConstant.SUBMIT,null);
        }else if(1==type){
            customerCreditAuditForm.setAuditStatus(CreditAuditConstant.FINALTRIAL);
            this.distributionOrder(customerCreditAuditForms,AuditOperationConstant.SAVE,null);
        }else if(3==type){
          this.finalBack(customerCreditAuditForms,4,letterTrialNoteRequest.getOperationId());
        }
    }

    /***
     * 分配订单,批量的  1 分配  2 初审退回  3 结案
     * @param customerCreditAuditForms
     */
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void distributionOrder(List<CustomerCreditAuditForm> customerCreditAuditForms,int type,String operationId){
        List<String> strs=new ArrayList<String>();
        for(CustomerCreditAuditForm customerCreditAuditForm:customerCreditAuditForms){
            customerCreditAuditForm.setStatus(1);
            strs.add(customerCreditAuditForm.getOrderId());
        }
        this.updateStatus(strs,type,operationId);
        customerCreditAuditMapper.distributionOrder(customerCreditAuditForms);
    }

    private void updateStatus(List<String> orderIds,int type,String operationId){
        OperationLogRequest operationLogRequest=new OperationLogRequest();
        String order="";
        for(int i=0;i<orderIds.size();i++){
          if(i<orderIds.size()-1){
              order=order+orderIds.get(i)+",";
          }else{
              order=order+orderIds.get(i);
          }
        }
        operationLogRequest.setOrderId(order);//插入订单号
        operationLogRequest.setOperationId(operationId);
        List<OperationLog> operationLogs=new ArrayList<OperationLog>();
        OperationLog operationLog=new OperationLog();
        List<Integer>  status=new ArrayList<Integer>();
        //分配
        if(AuditOperationConstant.DISTRIBUTION==type){
            status.add(CreditAuditConstant.UNALLOCATED);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.FIRSTTRIAL);
            operationLog.setModifyBefore("未分配");
            operationLog.setModifyAfter("未处理");
            operationLog.setOperationType("分配");
            operationLogs.add(operationLog);
        }
        //初审退回
        else if(AuditOperationConstant.INTINITALRETURN==type){
            status.add(CreditAuditConstant.FIRSTTRIAL);
            status.add(CreditAuditConstant.FINALRETURN);
            status.add(CreditAuditConstant.TRIALSAVE);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.UNALLOCATED);
            for(String str:orderIds){
                List<CustomerCreditAuditVO> customerCreditAuditVO=customerCreditAuditMapper.getCreditAuditVOByOrderId(str);
                operationLog.setModifyAfter("未分配");
                int auditStatus=customerCreditAuditVO.get(0).getAuditStatus();
                if(CreditAuditConstant.FIRSTTRIAL==auditStatus){
                    operationLog.setModifyBefore("未处理");
                }else if(CreditAuditConstant.FINALRETURN==auditStatus){
                    operationLog.setModifyBefore("终审退回");
                }else if(CreditAuditConstant.TRIALSAVE==auditStatus){
                    operationLog.setModifyBefore("暂存");
                }
                operationLog.setOperationType("初审退回");
                operationLogs.add(operationLog);
            }

        }
        //结案
        else if(AuditOperationConstant.FINALRETURN==type){
            status.add(CreditAuditConstant.FINALTRIAL);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.CASEEND);
            operationLog.setModifyBefore("终审");
            operationLog.setModifyAfter("结案");
            operationLog.setOperationType("结案");
            operationLogs.add(operationLog);
        }
        //终审退回
        else if(AuditOperationConstant.CASEEND==type){
            status.add(CreditAuditConstant.FINALTRIAL);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.FINALRETURN);
            operationLog.setModifyBefore("终审");
            operationLog.setModifyAfter("终审退回");
            operationLog.setOperationType("终审退回");
            operationLogs.add(operationLog);
        }else if(AuditOperationConstant.SUBMIT==5){
            status.add(CreditAuditConstant.FIRSTTRIAL);
            status.add(CreditAuditConstant.FINALRETURN);
            status.add(CreditAuditConstant.TRIALSAVE);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.FINALTRIAL);
            return;
        }else if(AuditOperationConstant.SAVE==6){
            status.add(CreditAuditConstant.FIRSTTRIAL);
            status.add(CreditAuditConstant.FINALRETURN);
            status.add(CreditAuditConstant.TRIALSAVE);
            customerCreditAuditMapper.updateStatus(orderIds,status,CreditAuditConstant.TRIALSAVE);
            return;
        }
        operationLogRequest.setOperationLogContentList(operationLogs);
        this.saveOperationLog(operationLogRequest);
    }

    /***
     *
     * @param customerCreditAuditForms
     * @param type  4 代表终审回退
     * @return
     */
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public String finalBack( List<CustomerCreditAuditForm> customerCreditAuditForms,int type,String operationId){
        List<String> lists=new ArrayList<String>();
        for(CustomerCreditAuditForm customerCreditAuditForm  :customerCreditAuditForms){
            customerCreditAuditForm.setAuditStatus(CreditAuditConstant.FINALRETURN);
            List<CustomerCreditAuditVO> customerCreditAuditVOs=customerCreditAuditMapper.
                    getCreditAuditVOByOrderId(customerCreditAuditForm.getOrderId());
            CustomerCreditAuditVO customerCreditAuditVO=customerCreditAuditVOs.get(0);
            customerCreditAuditForm.setUserId(customerCreditAuditVO.getUserId());
            customerCreditAuditForm.setStatus(1);
            customerCreditAuditForm.setReviewer(customerCreditAuditVO.getReviewer());
            lists.add(customerCreditAuditForm.getOrderId());
        }
        this.updateStatus(lists,type,operationId);
        customerCreditAuditMapper.distributionOrder(customerCreditAuditForms);
        return null;
    }


}
